package com.orhon.smartcampus.modules.systemctl.fetcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.orhon.smartcampus.modules.user.dao.UsersDao;
import com.orhon.smartcampus.modules.user.entity.Users;
import com.orhon.smartcampus.modules.user.gqlModel.GQLUser;
import com.orhon.smartcampus.modules.user.mm.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.entity.Grades;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.entity.Subjects;
import com.orhon.smartcampus.modules.base.gqlModel.GQLGrades;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSubject;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.GradeMapper;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.base.mm.SubjectMapper;
import com.orhon.smartcampus.modules.systemctl.dao.OrgDepartmentsDao;
import com.orhon.smartcampus.modules.systemctl.entity.OrgDepartments;
import com.orhon.smartcampus.modules.systemctl.entity.OrgDuties;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLDepartment;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLDuty;
import com.orhon.smartcampus.modules.systemctl.mm.DepartmentMapper;
import com.orhon.smartcampus.modules.systemctl.mm.DutiesMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.R;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class DepartmentsFetcher implements DataFetcher {


    @Autowired
    OrgDepartmentsDao orgDepartmentsDao;

    @Autowired
    UsersDao usersDao;

    @Autowired
    TokenService tokenService;

    /**
     * 获取部门列表
     *
     * @param environment
     * @return
     * @throws Exception editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        List<GQLDepartment> departments = new ArrayList<>();

        String token = tokenService.getSystemToken();
        if(token==null) {
            return  R.NoLogin();
        }
        Long schoolId = JwtUtils.getSchoolId(token);

        GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(environment);
        String hql = "from OrgDepartments where deleted_at = null ";

        if (environment.containsArgument("condition")) {
            HashMap<String, Object> map = ObjectToMap.to(environment.getArgument("condition"));
            if (map.get("id") != null) {
                hql += " and id =" + map.get("id");
            }
            if (map.get("department_name") != null) {
                hql += " and department_name " + Util.decide(map.get("department_name"));
            }
            if (map.get("parent_id") != null) {
                hql += " and parent_id " + Util.decide(map.get("parent_id"));
            }else{
                hql += " and parent_id is null ";
            }
            if (map.get("type") != null) {
                hql += " and type " + Util.decide(map.get("type"));
            }
            if (map.get("group_type") != null) {
                hql += " and group_type " + Util.decide(map.get("group_type"));
            }
            if (map.get("status") != null) {
                hql += " and status " + Util.decide(map.get("status"));
            }
            if (map.get("school_id") != null) {
                hql += " and school_id " + Util.decide(map.get("school_id"));
            }else {
            	hql += " and school_id = " +schoolId;
            }
        }
        System.out.println(hql);
        List<OrgDepartments> list = orgDepartmentsDao.find(hql, null, page.getPage(), page.getLimit());


        for (OrgDepartments item : list) {
            GQLDepartment gqlDepartment = null;
            if (environment.getSelectionSet().contains("data/parent")) {
                OrgDepartments parent = item.getSystemctlOrgDepartmentsByParentId();
                gqlDepartment = DepartmentMapper.MAPPER.toOrgDepartments(parent);
            }
            GQLSchool gqlSchool = null;
            if (environment.getSelectionSet().contains("data/school")) {
                Schools schools = item.getBaseSchoolsBySchoolId();
                gqlSchool = SchoolMapper.MAPPER.toSchool(schools);
            }
            List<GQLDepartment> gqlChildreen = null;
            if (environment.getSelectionSet().contains("data/childreen")) {
                List<OrgDepartments> childreen = item.getChildreen();
                gqlChildreen = DepartmentMapper.MAPPER.toOrgDepartmentsList(childreen);
            }
            List<GQLDuty> gqlDuty = null;
            if (environment.getSelectionSet().contains("data/duties")) {
                List<OrgDuties> orgDuties = item.getDuties();
                gqlDuty = DutiesMapper.MAPPER.toOrgDutiesList(orgDuties);
                if(gqlDuty.size() > 0){
                    for (GQLDuty duty: gqlDuty){
                        if(orgDuties != null){
                            String userhql = "from Users where deleted_at = null and id in ( select userUsersByUserId from OrgDepartmentUserRelation where deletedAt = null "+" and department_id = "+item.getId()+" and duty_id = "+duty.getId() + ")";
                            List<Users> userList = usersDao.find(userhql);
                            List<GQLUser> gqlUserList = UserMapper.MAPPER.mapList(userList);
                            duty.setUserList(gqlUserList);
                        }
                    }
                }
            }
            List<GQLGrades> gqlGrades = null;
            if (environment.getSelectionSet().contains("data/grade")) {
                List<Grades> grade = item.getGrades();
                gqlGrades = GradeMapper.MAPPER.toGradeList(grade);
            }
            List<GQLSubject> gqlSubject = null;
            if (environment.getSelectionSet().contains("data/subject")) {
                List<Subjects> subject = item.getSubjects();
                gqlSubject = SubjectMapper.MAPPER.toSubjectList(subject);
            }
            GQLDepartment department = DepartmentMapper.MAPPER.toOrgDepartments(item);
            department.setSchool(gqlSchool);
            department.setParent(gqlDepartment);
            department.setChildreen(gqlChildreen);
            department.setDuties(gqlDuty);
            department.setGrade(gqlGrades);
            department.setSubject(gqlSubject);
            departments.add(department);
        }

        Long total = 0L;
        if (environment.getSelectionSet().contains("total")) {
            total = orgDepartmentsDao.getTotalCount(hql);
        }
        return Result.ok().put("data", departments).put("total", total);
    }
}
